/*
 * Copyright (c) 2010, Christian Lerche
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the Institute nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * Author: Christian Lerche <christian.lerche@uni-rostock.de>
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>

#define PRINT_MSG             0
#define MTU                   5000
#define MSG_BUF_LEN           10000
#define WAIT_FOR_ANSWER       1

/* global message buffer */
char msg_buf[MSG_BUF_LEN + 1];

static int load_file(const char *filename, char **buf);

int main(int argc, char *argv[]) {
    char* buf;
    int buf_len, msg_len;
    int r;
    int result = 0;
    struct addrinfo *ai;
    struct addrinfo hints;
    struct timeval tv1, tv2;
    long int u_sec;

    if (argc < 4) {
        printf("Parameter list: [ipadress] [port] [request-file]\n");
        printf("NOTE: for link-local you need to specify the interface! (e.g.: fe80::1%%eth0)\n");
        exit(-1);
    }

    /* load file */
    buf_len = load_file(argv[3], &buf);
    if (buf_len < 0) {
        printf("Error: unknown file (%s)\n", argv[3]);
        exit(EXIT_FAILURE);
    }

    /* Add HTTP Header */
    sprintf(msg_buf, "POST / HTTP/1.1\r\nCONTENT-TYPE: application/soap+xml\r\nCONTENT-LENGTH: %i\r\n\r\n", buf_len);

    /* copy file content in msg_buf*/
    msg_len = strlen(msg_buf);
    memcpy(&msg_buf[msg_len], buf, buf_len);
    msg_len += buf_len;
    msg_buf[msg_len] = '\0';

    memset(&hints, '\0', sizeof(hints));
    hints.ai_socktype = SOCK_STREAM;

    int e = getaddrinfo(argv[1], argv[2], &hints, &ai);
    if (e) {
        printf("Error: getaddrinfo: %s\n", gai_strerror(e));
        exit(EXIT_FAILURE);
    }

    struct addrinfo *runp = ai;
    while (runp != NULL) {
        int sock = socket(runp->ai_family, runp->ai_socktype, runp->ai_protocol);
        if (sock != -1) {
            if (gettimeofday(&tv1, NULL)) {
                printf("ERROR: gettimeofday\n");
                exit(EXIT_FAILURE);
            }
            /*TODO: using runp->ai_addr-> is not so good. How to make it better?*/
            if (connect(sock, runp->ai_addr, runp->ai_addrlen) == 0) {
                char* send_buf = msg_buf;
                int send_len, rest_len = msg_len;
                do {
                    send_len = rest_len;
                    /* send not more than the MTU*/
                    if (send_len > MTU) {
                        send_len = MTU;
                    }
                    /* SEND */
                    if (send(sock, send_buf, send_len, 0) < 0) {
                        perror("send");
                        close(sock);
                        exit(EXIT_FAILURE);
                    }
#if PRINT_MSG
                    /* DEBUG */
                    printf("[MSG]");
                    for (i = 0; i < send_len; i++)
                    putchar(send_buf[i]);
                    printf("[END]\n");
#endif /* PRINT_MSG */
                    send_buf += send_len;
                    rest_len -= send_len;
                } while (rest_len != 0);
#if WAIT_FOR_ANSWER
                int read_buf_len = 0;
                //printf("Waiting for the answer...\n");
                while (1) {
                    r = read(sock, &msg_buf[read_buf_len], MSG_BUF_LEN);
                    if (r <= 0) {
                        printf("socket closed... finish now\n");
                        break;
                    }
                    read_buf_len += r;
                }
                msg_buf[read_buf_len] = '\0';
                printf("Read %i bytes:\n", read_buf_len);
                printf("%s\n", msg_buf);
#endif /*WAIT_FOR_ANSWER*/
                if (gettimeofday(&tv2, NULL)) {
                    printf("ERROR: gettimeofday\n");
                    exit(EXIT_FAILURE);
                }
                u_sec = ((tv2.tv_sec - tv1.tv_sec) * 1000000) + tv2.tv_usec - tv1.tv_usec;
                printf("Roundtrip: %lu usec\n", u_sec);
                printf("Req: %i bytes\n", msg_len);
                printf("Resp: %i bytes\n", read_buf_len);

                close(sock);
                goto out;
            }

            close(sock);
        }
        runp = runp->ai_next;
    }
    printf("Error: cannot contact %s\n", argv[1]);
    exit(EXIT_FAILURE);
    result = 1;
    out: freeaddrinfo(ai);
    return result;
}

static int load_file(const char *filename, char **buf) {
    int total_bytes = 0;
    int bytes_read = 0;
    int filesize;
    FILE *stream = fopen(filename, "rb");

    if (stream == NULL) {
        return -1;
    }

    fseek(stream, 0, SEEK_END);
    filesize = ftell(stream);
    *buf = malloc(filesize);
    fseek(stream, 0, SEEK_SET);

    do {
        bytes_read = fread(*buf + total_bytes, 1, filesize - total_bytes, stream);
        total_bytes += bytes_read;
    } while (total_bytes < filesize && bytes_read > 0);

    fclose(stream);
    return filesize;
}

